package com.whl.sm.controller.expense;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.common.util.ExcelUtils;
import com.whl.sm.controller.BaseController;
import com.whl.sm.dto.ImportRecordDto;
import com.whl.sm.model.assets.ComUnits;
import com.whl.sm.model.expense.MaterBill;
import com.whl.sm.model.expense.MaterRecord;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.assets.ComUnitsService;
import com.whl.sm.service.expense.MaterBillService;
import com.whl.sm.service.expense.MaterRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Executable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2021-10-18
 */
@Slf4j
@RestController
@RequestMapping("/mater-record")
public class MaterRecordController extends BaseController {

    @Autowired
    private MaterRecordService materRecordService;

    @Autowired
    private ComUnitsService  comUnitsService;

    @Autowired
    private MaterBillService materBillService;

    @RequestMapping("/list")
    public Result getRecord(HttpServletRequest request){
        QueryWrapper queryWrapper = new QueryWrapper();
        setHttpRequestQueryWrapper(queryWrapper,"mater_type","unit_id","overdue");
        queryWrapper.ne("is_del",1);
        queryWrapper.orderByDesc("overdue");
        queryWrapper.orderByDesc("update_time");
        Page<Object> recordPage = materRecordService.page(getPage(),queryWrapper);
        recordPage.getRecords().stream().forEach(obj->{
            MaterRecord materRecord = (MaterRecord) obj;
            ComUnits linkUnit  = comUnitsService.getById(materRecord.getUnitId());
            materRecord.setUnitCode(linkUnit!=null?linkUnit.getUnitCode():"");
            Integer hasBill = materBillService.count(new QueryWrapper<MaterBill>()
                    .eq("mater_record_id",materRecord.getId())
                    .ne("is_del",1)
            );
            materRecord.setHasBill(hasBill>0?true:false);
        });
        return Result.ok(recordPage);
    }

    @RequestMapping("/info/{id}")
    public Result materRecord(@PathVariable("id") String id){
        MaterRecord materRecord = materRecordService.getById(id);
        return Result.ok(materRecord);
    }


    @RequestMapping("/update")
    public Result updateMaterBill(@RequestBody MaterRecord materRecord){
        return materRecordService.update(materRecord);

    }

    @RequestMapping("/logDelete")
    public Result logicalDelete(@RequestBody List<String> idList){
        for (int i = 0; i <idList.size() ; i++) {
            materRecordService.update(new UpdateWrapper<MaterRecord>()
                    .eq("id",idList.get(i))
                    .set("is_del",1)
            );
        }
        return Result.ok();
    }


    @PostMapping("/buildBill")
    public Result buildBill(@RequestParam String waterId, @RequestParam String electricId,  @RequestParam List<String> idList){
       return materRecordService.addBillOfMater(waterId,electricId,idList);
    }


    @RequestMapping("/uploadFile")
    public Result importRecord(@RequestParam MultipartFile file,HttpServletRequest request){
        List<ImportRecordDto> list = null;
        StringBuffer errorInfo = null;
        try {
            String fileName = file.getOriginalFilename();
            //获取上传的excel文件名后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);
            if (!fileSuffix.equals("xls")){
                return Result.build(444,"请选择正确文件");
            }
            log.info("excel2003版本");

            Workbook wb=new HSSFWorkbook(file.getInputStream()); //获取excel工作簿

            Sheet sheet=wb.getSheetAt(0);  //获取excel的sheet

            if(sheet==null) {
                return Result.build(444,"请选择正确文件");
            }

            list = new ArrayList<ImportRecordDto>();

            //循环获取excel每一行
            for(int rowNum=1;rowNum<sheet.getLastRowNum()+1;rowNum++) {
                Row row=sheet.getRow(rowNum);
                if(row==null) {
                    continue;
                }

                ImportRecordDto record = new ImportRecordDto();

                //循环获取excel每一行的每一列
                for(int cellNum=0;cellNum<row.getLastCellNum();cellNum++) {
                    Cell cell=row.getCell(cellNum);
                    SimpleDateFormat pat = new SimpleDateFormat("yyyy-MM-dd");
                    if(cell==null) {
                        continue;
                    }
                    if(cellNum==0) {
                        String unitCode = String.valueOf(ExcelUtils.getValue(cell));
                        if (unitCode.contains(".")){
                            String[] splitStr = unitCode.split("\\.");
                            unitCode = splitStr.length>0?splitStr[0]:"";
                        }
                        record.setUnitCode(unitCode);
                    }else if(cellNum==1) {
                        record.setMaterType((String) ExcelUtils.getValue(cell));
                    }else if(cellNum==2) {
                        record.setMaterRecord((Double) ExcelUtils.getValue(cell));
                    }else if(cellNum==3) {
                        Date date = pat.parse((String) ExcelUtils.getValue(cell));
                        record.setCurrentRecordTime(date);
                    }
                }
                list.add(record);    //将excel每一行的数据封装到user对象,并将user对象添加到list

            }

        }catch (Exception e){
            log.error("小水电表数据导入失败:"+e.getMessage());
            return Result.build(444,"导入失败,请检查数据");
        }
        return materRecordService.beachAddRecord(list);
    }


}
